package com.twang.stock.feign;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.jayway.jsonpath.JsonPath;
import com.twang.stock.entity.EbayMerchantInfo;
import com.twang.stock.mapper.EbayMerchantInfoMapper;
import com.twang.stock.service.jinyan.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

@Slf4j
@Service
public class EbayApiClient {
    @Resource
    private EbayMerchantInfoMapper ebayMerchantInfoMapper;

    @Autowired
    private CommonService commonService;
    // DTO Classes
    public static class ApiResponse {
        @JsonProperty("deferred_modules")
        public List<DeferredModule> deferredModules = new ArrayList<>();
    }

    public static class ApiResponseModules {
        @JsonProperty("modules")
        public List<DeferredModule> modules = new ArrayList<>();
    }

    public static class DeferredModule {
        private final Map<String, Object> listings = new LinkedHashMap<>();

        @JsonAnySetter
        public void addListing(String key, Object value) {
            listings.put(key, value);
        }

        @JsonAnyGetter
        public Map<String, Object> getListings() {
            return listings;
        }
    }

    public static class Item {
        @JsonProperty("_type")
        public String type;
        @JsonProperty("action")
        public Action action;
        @JsonProperty("listingId")
        public String listingId;
        @JsonProperty("title")
        public Title title;
        @JsonProperty("image")
        public Image image;
        @JsonProperty("displayPrice")
        public Price displayPrice;
        @JsonProperty("quantity")
        public Quantity quantity;
        // 新增搜索信息字段
        // 保留原字段名，但通过 @JsonDeserialize 指定自定义解析器
        @JsonDeserialize(using = CustomSearchDeserializer.class)
        public SearchInfo searchInfo;
    }

    // 自定义反序列化器
    public class CustomSearchDeserializer extends JsonDeserializer<SearchInfo> {
        @Override
        public SearchInfo deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            ObjectCodec codec = p.getCodec();
            JsonNode node = codec.readTree(p);
            return codec.treeToValue(node.get("__search"), SearchInfo.class);
        }
    }

    public static class Action {
        @JsonProperty("_type")
        public String actionType;
        @JsonProperty("type")
        public String type;
        @JsonProperty("name")
        public String name;
        @JsonProperty("params")
        public Map<String, Object> params;
        @JsonProperty("trackingList")
        public List<Tracking> trackingList;
        @JsonProperty("URL")
        public String url;
    }

    // 新增搜索信息DTO
    public static class SearchInfo {
        @JsonProperty("watchCountTotal")
        public WatchCountTotal watchCountTotal;
        @JsonProperty("itemLocation")
        public TextSpan itemLocation;
        @JsonProperty("sellerInfo")
        public SellerInfo sellerInfo;
        @JsonProperty("defaultWatchIconOnImage")
        public WatchButton defaultWatchIconOnImage;
        @JsonProperty("brandName")
        public String brandName;
    }

    // 新增子DTO类
    public static class WatchCountTotal {
        @JsonProperty("text")
        public IconAndText text;
    }

    public static class SellerInfo {
        @JsonProperty("text")
        public IconAndText text;
    }

    public static class WatchButton {
        @JsonProperty("watch")
        public IconAndText watch;
        @JsonProperty("watching")
        public IconAndText watching;
        @JsonProperty("isWatching")
        public boolean isWatching;
    }

    public static class IconAndText {
        public Icon icon;
        public TextualDisplay text;
    }

    public static class TextualDisplay {
        @JsonProperty("textSpans")
        public List<TextSpan> textSpans;
        @JsonProperty("accessibilityTexts")
        public List<AccessibilityText> accessibilityTexts;
    }


    public static class AccessibilityText {
        @JsonProperty("text")
        public String text;
    }

    public static class Icon {
        @JsonProperty("name")
        public String name;
    }

    public static class Title {
        @JsonProperty("textSpans")
        public List<TextSpan> textSpans;

        public String getText() {
            return textSpans.get(0).text;
        }
    }

    public static class TextSpan {
        @JsonProperty("text")
        public String text;
    }

    public static class Image {
        @JsonProperty("title")
        public String title;
        @JsonProperty("imageId")
        public String imageId;
        @JsonProperty("URL")
        public String url;
    }

    public static class Price {
        @JsonProperty("value")
        public Amount value;
    }

    public static class Amount {
        @JsonProperty("value")
        public double value;
        @JsonProperty("currency")
        public String currency;
    }

    public static class Quantity {
        @JsonProperty("value")
        public int value;
    }

    public static class Tracking {
        @JsonProperty("actionKind")
        public String actionKind;
    }

//    public static void main(String keyValu,int page) {
//        try {
//            // 1. 创建HTTP连接
//            URL url = new URL("https://apisd.ebay.com/experience/search/v1/search_results?answersVersion=1&_pgn=" + page + "&async=false&_sop=12&_nkw=Buccellati+from+china&_vs=1&supportedUxComponentNames=ITEM_CARD,DENSE_ITEM_CARD,REWRITES_ITEMS,REWRITE_START,BASIC_MESSAGE,TWO_LINE_MESSAGE,BASIC_USER_MESSAGE,BASIC_SELLER_HEADER,PROMOTED_ITEM_CARD,VEHICLE_PARTS_FINDER,MOTORS_TIRE_FINDER,TOP_OF_PAGE_FINDER,TOP_OF_PAGE_WITH_VEHICLE,TOP_OF_PAGE_TIRE,GARAGE_ONE_CLICK_FINDER,UNIVERSAL_FINDER,STATUS_BAR_V2,ICON_MESSAGE,TOGGLE_MESSAGE,STORE_INFORMATION,PRESENCE_INFORMATION_V3,FIRST_PARTY_ADS_BANNER,ITEMS_CAROUSEL_V3,NAVIGATION_ANSWER_PILL_CAROUSEL,NAVIGATION_IMAGE_ANSWER_CAROUSEL,NAVIGATION_ANSWER_TEXT_LIST,NAVIGATION_ANSWER_SIMPLE_IMAGE_CAROUSEL,IMAGE_ANSWER_GUIDANCE_CAROUSEL,PAGE_TITLE_BAR,ASPECTS_IN_RIVER,ITEM_CAROUSEL_BOS,GRID_VIEW_ITEM_CAROUSEL_BOS,EDUCATION,SAVED_ASPECTS_ENTRY,SAVED_ASPECTS_SNACKBAR,IMAGE_ANSWER_TABBED_CAROUSEL,SNACK_BAR,COLD_START_BOTTOM_DRAWER_FINDER,SAVE_CARD,AD_PD_S2,SPECTRUM_OF_VALUE_CAROUSEL,EEK_ICON,SPONSORED_BADGE,ITEMS_CAROUSEL_WITH_COLOR,SELLER_OFFER_TAPPABLE_HEADER,BOS_PLACEHOLDER,CAQ_PLACEHOLDER,INSIGHTS,SEEK_FEEDBACK_COMPONENT,SEARCH_PRICE_TRENDS,ORGANIZED_RESULTS_CAROUSEL,NAVIGATION_ANSWER_TOGGLE_WITH_PILL_CAROUSEL,BUTTON_WITH_MESSAGE,SEARCH_OSR_MAG_CAROUSEL,ORGANIZED_RESULTS_GRID,OSR_BY_KEYWORDS_CAROUSEL,MODEL_PRICE_GUIDANCE,PBE_MODEL,MODELS_CAROUSEL,PBE_SERIES,PBE_MODEL,MODELS_CAROUSEL,PBE_PRICE_HISTORY&requestedPageLayoutsForMultiLayoutRegion=LIST_1_COLUMN,LARGE_1_COLUMN,GRID_2_COLUMN&enableDeferredModules=1"); // URL参数已简化
//            // String resutlt=  getPage111("",url);
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setRequestMethod("GET");
//            connection.setRequestProperty("Accept-Charset", "UTF-8"); // 设置请求编码
//            // 2. 设置请求头
//            setRequestHeaders(connection);
//
//            // 3. 获取响应
//            int responseCode = connection.getResponseCode();
//            if (responseCode == HttpURLConnection.HTTP_OK) {
//                // 4. 读取响应内容
//                String response = readResponse(connection);
//
//                // 5. 解析JSON
//                ObjectMapper mapper = new ObjectMapper();
//                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//
//                ApiResponse apiResponse = mapper.readValue(response, ApiResponse.class);
//                System.out.println("成功解析 " + apiResponse.deferredModules.size() + " 个模块");
//                // 6. 处理结果
//                processResponse(apiResponse,keyValu);
//            } else {
//                System.out.println("HTTP请求失败，状态码: " + responseCode);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    public  void getByPage(String keyValu,int page) {
        try {
            String  fsynfals = "false";
            if (page > 1) {
                fsynfals = "true";
            }
            // 1. 创建HTTP连接
            URL url = new URL("https://apisd.ebay.com/experience/search/v1/search_results?answersVersion=1&_pgn=" + page + "&async=" + fsynfals + "&_sop=12&_nkw=" + keyValu + "&_vs=1&supportedUxComponentNames=ITEM_CARD,DENSE_ITEM_CARD,REWRITES_ITEMS,REWRITE_START,BASIC_MESSAGE,TWO_LINE_MESSAGE,BASIC_USER_MESSAGE,BASIC_SELLER_HEADER,PROMOTED_ITEM_CARD,VEHICLE_PARTS_FINDER,MOTORS_TIRE_FINDER,TOP_OF_PAGE_FINDER,TOP_OF_PAGE_WITH_VEHICLE,TOP_OF_PAGE_TIRE,GARAGE_ONE_CLICK_FINDER,UNIVERSAL_FINDER,STATUS_BAR_V2,ICON_MESSAGE,TOGGLE_MESSAGE,STORE_INFORMATION,PRESENCE_INFORMATION_V3,FIRST_PARTY_ADS_BANNER,ITEMS_CAROUSEL_V3,NAVIGATION_ANSWER_PILL_CAROUSEL,NAVIGATION_IMAGE_ANSWER_CAROUSEL,NAVIGATION_ANSWER_TEXT_LIST,NAVIGATION_ANSWER_SIMPLE_IMAGE_CAROUSEL,IMAGE_ANSWER_GUIDANCE_CAROUSEL,PAGE_TITLE_BAR,ASPECTS_IN_RIVER,ITEM_CAROUSEL_BOS,GRID_VIEW_ITEM_CAROUSEL_BOS,EDUCATION,SAVED_ASPECTS_ENTRY,SAVED_ASPECTS_SNACKBAR,IMAGE_ANSWER_TABBED_CAROUSEL,SNACK_BAR,COLD_START_BOTTOM_DRAWER_FINDER,SAVE_CARD,AD_PD_S2,SPECTRUM_OF_VALUE_CAROUSEL,EEK_ICON,SPONSORED_BADGE,ITEMS_CAROUSEL_WITH_COLOR,SELLER_OFFER_TAPPABLE_HEADER,BOS_PLACEHOLDER,CAQ_PLACEHOLDER,INSIGHTS,SEEK_FEEDBACK_COMPONENT,SEARCH_PRICE_TRENDS,ORGANIZED_RESULTS_CAROUSEL,NAVIGATION_ANSWER_TOGGLE_WITH_PILL_CAROUSEL,BUTTON_WITH_MESSAGE,SEARCH_OSR_MAG_CAROUSEL,ORGANIZED_RESULTS_GRID,OSR_BY_KEYWORDS_CAROUSEL,MODEL_PRICE_GUIDANCE,PBE_MODEL,MODELS_CAROUSEL,PBE_SERIES,PBE_MODEL,MODELS_CAROUSEL,PBE_PRICE_HISTORY&requestedPageLayoutsForMultiLayoutRegion=LIST_1_COLUMN,LARGE_1_COLUMN,GRID_2_COLUMN&enableDeferredModules=1"); // URL参数已简化
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept-Charset", "UTF-8"); // 设置请求编码

            connection.setConnectTimeout(10_000); // 10秒连接超时
            connection.setReadTimeout(30_000);    // 30秒读取超时
            // 2. 设置请求头
            String token= commonService.getBaseCommon("ebay_api_token").getCommonValue();
            setRequestHeaders(connection,token);

            // 3. 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 4. 读取响应内容
                String response = readResponse(connection);

                // 5. 解析JSON
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

                ApiResponse apiResponse = mapper.readValue(response, ApiResponse.class);
                System.out.println("成功解析 " + apiResponse.deferredModules.size() + " 个模块");
                if(apiResponse.deferredModules.size()<1) {
                    EbaySearchResponse ebaySearchResponse = mapper.readValue(response, EbaySearchResponse.class);
                    List<EbayMerchantInfo> ebayMerchantInfos = Lists.newArrayList();
                    for(Object obj1: ebaySearchResponse.getAllListings()) processModuls(keyValu, obj1, ebayMerchantInfos);
                    if(CollectionUtils.isNotEmpty(ebayMerchantInfos)){
                        ebayMerchantInfoMapper.batchInsert(ebayMerchantInfos);
                    }
                }else {
                    // 6. 处理结果
                    processResponse(apiResponse,null, keyValu);
                }

            } else {
                System.out.println("HTTP请求失败，状态码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void processModuls(String keyValu, Object obj1, List<EbayMerchantInfo> ebayMerchantInfos) {
        //
        try {
            EbayMerchantInfo ebayMerchantInfo = new EbayMerchantInfo();

            String obj = JSONObject.toJSONString(obj1);
            //URL
            String URL = JsonPath.read(obj, "$.action.URL").toString();
            if (StringUtils.isNotEmpty(URL)) {
                ebayMerchantInfo.setName(keyValu.replace("+"," "));
                ebayMerchantInfo.setHomePage(URL);
                //displayPrice
                String sellerInfo = JsonPath.read(obj, "$.__search.sellerInfo.text.textSpans[0].text").toString();
                ebayMerchantInfo.setHomePageName(sellerInfo.split(" \\(")[0]);
                ebayMerchantInfo.setScore(Integer.parseInt(sellerInfo.split(" \\(")[1].split("\\)")[0].replace(",", "")));

                //itemLocation
                String itemLocation = JsonPath.read(obj, "$.__search.itemLocation.text").toString();
                ebayMerchantInfo.setLocalStation(itemLocation.split("：")[1]);
                if(!(ebayMerchantInfo.getLocalStation().contains("中国")||ebayMerchantInfo.getLocalStation().contains("china")
                        ||ebayMerchantInfo.getLocalStation().contains("CHINA"))){
                    String ebay_api_location = commonService.getBaseCommon("ebay_api_location").getCommonValue();
                    if(!"CLOSE".equals(ebay_api_location)){
                        return;
                    }
                }
                ebayMerchantInfos.add(ebayMerchantInfo);
            }
        } catch (Exception exception) {
            log.info("error -- >", exception);
        }
    }

    /**
     * 文件处理器
     * @param response
     * @param keyValue
     * @throws JsonProcessingException
     */
    public void processResponseMessage( String response,String keyValue) throws JsonProcessingException {
        // 5. 解析JSON
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        ApiResponse apiResponse = mapper.readValue(response, ApiResponse.class);
        System.out.println("成功解析 " + apiResponse.deferredModules.size() + " 个模块");
        if(apiResponse.deferredModules.size()<1) {
            ApiResponseModules apiResponseModules = mapper.readValue(response, ApiResponseModules.class);
<<<<<<< HEAD
            String models = JsonPath.read(response, "$.modules").toString();
            List<DeferredModule> modules =  JSONObject.parseArray(models,DeferredModule.class);
=======
            String module = JsonPath.read(response, "$.modules").toString();
            List<DeferredModule> modules = JSONObject.parseArray(module, DeferredModule.class);
>>>>>>> 59e82afd2f3486f0a4bf000501121c4c010b9436
            apiResponseModules.modules.addAll(modules);
            // 6. 处理结果
            processResponse(null, apiResponseModules, keyValue);
        }else {
            // 6. 处理结果
            processResponse(apiResponse,null, keyValue);
        }
    }




    private static void setRequestHeaders(HttpURLConnection connection,String token) {
//            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        connection.setRequestProperty("Accept-Language", "zh-CN");
        connection.setRequestProperty("Accept", "application/json;presentity=inline");
        connection.setRequestProperty("Authorization", token);
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Host", "apisd.ebay.com");
        connection.setRequestProperty("User-Agent", "eBayiPhone/6.198.0");
        connection.setRequestProperty("X-EBAY-4PP", "AQADS7sru295Pvp2EhbY3JSLOykgYqO0WOcpTmtH5HBkN7akGw/z5arBh6sd4Ns4pbNU");
        connection.setRequestProperty("X-EBAY-C-CORRELATION-SESSION", "devicetimestamp=2025-04-04T11:06:23.774Z,si=5da13b9b19595f7048cf9c10011a03b1,sid=p--2048309.m--2618.l--1312");
        connection.setRequestProperty("X-EBAY-C-CULTURAL-PREF", "Currency=USD,Timezone=Asia/Shanghai,Units=Metric");
        connection.setRequestProperty("X-EBAY-C-ENDUSERCTX", "contextualLocation=country%3DUS,deviceId=1955da157ac.a3521b2.48e1f.ffff9215,deviceIdType=IDREF,userAgent=ebayUserAgent/eBayIOS;6.198.0;iOS;18.3.2;Apple;iPhone17_2;--;440x956;3.0");
        connection.setRequestProperty("X-EBAY-C-EXP", "noepheader=1,eprlogid=t6fuuq%60fiiw%3F%3Cbsvpd%60jhs.%3D3342da4c2*nv3ip-196007a8ac3-0x233e,c=5,v=v2,uit=1741032649");
        connection.setRequestProperty("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
        connection.setRequestProperty("X-EBAY-C-REQUEST-AUTH-DEBUG", "hkh=pBTcML3+u1FSVJsdvKzk00AXlk8gmOLIRJy+ac3fjIc=;guid=5da13b9b19595f7048cf9c10011a03b1");
        connection.setRequestProperty("X-EBAY-C-REQUEST-ID", "rci=u/l5jbiYMSecGW5f");
        connection.setRequestProperty("X-EBAY-C-TERRITORY-ID", "US");
        connection.setRequestProperty("X-EBAY-C-TRACKING", "devicetimestamp=2025-04-04T11:06:23.774Z,guid=5da13b9b19595f7048cf9c10011a03b1,pageid=2351460");
        connection.setRequestProperty("ebay-ets-api-intent", "foreground");
        connection.setRequestProperty("ebay-ets-device-theme", "dark");
        connection.setRequestProperty("x-ebay-advertising", "deviceAdvertisingIdentifier=00000000-0000-0000-0000-000000000000,deviceTargetedAdvertisingOptOut=true");
    }

    private static String readResponse(HttpURLConnection connection) throws IOException {
        // 获取输入流时指定GBK编码
        try {
            String contentType = connection.getContentType();
            System.out.println("查看服务器返回的编码信息 Content-Type: " + contentType); // 查看服务器返回的编码信息
            // 使用字节流直接读取，避免逐行解析
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[2 * 1024 * 1024]; // 8KB 缓冲区
            int bytesRead;
            while ((bytesRead = inputStream.read(data)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            return buffer.toString(StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) { // [!code focus]
            throw new RuntimeException("不支持的编码格式", e);
        }
    }


    public  void processResponse(ApiResponse response,ApiResponseModules apiResponseModules,String keyValue) {
        List<EbayMerchantInfo> ebayMerchantInfos = Lists.newArrayList();
        List<DeferredModule> deferredModules = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(response.deferredModules)){
            deferredModules.addAll(response.deferredModules);
        }else{
            deferredModules.addAll(apiResponseModules.modules);

        }
        for (DeferredModule module : deferredModules) {
            for (Map.Entry<String, Object> entry : module.getListings().entrySet()) {
                //
                try {
                    EbayMerchantInfo ebayMerchantInfo = new EbayMerchantInfo();

                    String obj = JSONObject.toJSONString(entry.getValue());
                    //URL
                    String URL = JsonPath.read(obj, "$.action.URL").toString();
                    if (StringUtils.isNotEmpty(URL)) {
                        ebayMerchantInfo.setName(keyValue.replace("+"," "));
                        ebayMerchantInfo.setHomePage(URL);
                        //displayPrice
                        String sellerInfo = JsonPath.read(obj, "$.__search.sellerInfo.text.textSpans[0].text").toString();
                        ebayMerchantInfo.setHomePageName(sellerInfo.split(" \\(")[0]);
                        ebayMerchantInfo.setScore(Integer.parseInt(sellerInfo.split(" \\(")[1].split("\\)")[0].replace(",", "")));

                        //itemLocation
                        String itemLocation = JsonPath.read(obj, "$.__search.itemLocation.text").toString();
                        ebayMerchantInfo.setLocalStation(itemLocation.split("：")[1]);
                        if(!(ebayMerchantInfo.getLocalStation().contains("中国")||ebayMerchantInfo.getLocalStation().contains("china")
                                ||ebayMerchantInfo.getLocalStation().contains("CHINA"))){
                            String ebay_api_location = commonService.getBaseCommon("ebay_api_location").getCommonValue();
                            if("CLOSE".equals(ebay_api_location)){
                                continue;
                            }
                        }

                        ebayMerchantInfos.add(ebayMerchantInfo);
                    }
                } catch (Exception exception) {
                    log.info("error -- >", exception);
                }
            }
        }
        if(CollectionUtils.isNotEmpty(ebayMerchantInfos)){
            ebayMerchantInfoMapper.batchInsert(ebayMerchantInfos);
        }

    }
}
